package com.java.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.dao.UserDao;
import com.java.domain.SysUser;
import com.java.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    /**
     * 通过用户名得到用户对象
     * 创建用户详情对象，返回
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userDao.findByUsername(username);
        if (sysUser == null) {
            return null;
        }

        // 创建了角色的集合对象
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        // 创建临时的角色对象
        SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
        authorities.add(grantedAuthority);

        // 构建UserDetails类
//        UserDetails user = new User(sysUser.getUsername(), "{noop}" + sysUser.getPassword(), authorities); // 不加密
        UserDetails user = new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
        return user;
    }

    @Override
    public PageInfo<SysUser> findAllByPage(Integer currPage, Integer pageSize) {
        PageHelper.startPage(currPage, pageSize);
        List<SysUser> userList = userDao.findAll();
        return new PageInfo<>(userList);
    }

    @Override
    public void save(SysUser user) {
        userDao.save(user);
    }

    @Override
    public Boolean isUniqueUsername(String username) {
        SysUser user = userDao.findAllByUsername(username);
        return user == null;
    }

    @Override
    public SysUser findDetails(Integer userId) {
        SysUser user = userDao.findById(userId);
        return null;
    }
}
